#-*-coding:utf8;-*-
from matplotlib.pyplot import savefig
from numpy import flatiter, left_shift, nan
from numpy.lib.function_base import append
import pandas as pd
import time
import numpy as np
import mplfinance as mpf
import os
import tushare as ts
# from  chinese_calendar  import is_holiday
import datetime
from ylTDX import * #from ylTDX import all def function

pd.options.mode.chained_assignment = None #avoid :pandas SettingWithCopyWarning
ts.set_token("6667cd4a2326f2f937062a0f4fb59aea5c56d13b1f6f26225f115fe9")
"""
DRAWTEXT_FIX(1,0.00,0.00,0,'【趋势线注释：粉+红=满仓，粉+绿=六成，蓝+红=四成，蓝+绿=空仓】'),COLORRED;

VAR1:=IF(YEAR>2999 AND MONTH>5,0,1);
VAR2:=IF(HIGH=CLOSE,1.10*CLOSE,HIGH)*VAR1;
VAR3:=IF(HIGH=CLOSE,0.90*CLOSE,LOW)*VAR1;
短期值1:=EMA((HIGH+LOW)/2,5);
顶部线1:=EMA(EMA(VAR2,6)*1.05,8);
底部线1:=EMA(EMA(VAR3,6)*0.97,8);
VARA1:=EXPMA(CLOSE,5);
VARB1:=EXPMA(CLOSE,10);
VARC1:=EXPMA(CLOSE,20);
VARD1:=EXPMA(CLOSE,50);
VARE1:=(VARA1+VARB1+VARC1+VARD1)/4;
天线1:MA(VARE1,4);
天线2:=MA(VARE1,5)+MA(VARE1,5)*0.03;
天线3:MA(VARE1,4)-MA(VARE1,4)*0.03;
NOTEXT天线01:IF(天线1>REF(天线1,1),天线1,DRAWNULL),COLORRED;
NOTEXT天线11:IF(天线1<REF(天线1,1),天线1,DRAWNULL),COLORGREEN;
NOTEXT天线03:IF(天线3>REF(天线3,1),天线3,DRAWNULL),COLORRED;
NOTEXT天线13:IF(天线3<REF(天线3,1),天线3,DRAWNULL),COLORGREEN;
STICKLINE(天线1>REF(天线1,1),天线1,天线3,0,0),COLORRED;
STICKLINE(天线1<REF(天线1,1),天线1,天线3,0,0),COLORGREEN;

空:=REF(C,1)>REF(天线3,1) AND C<天线3;
多:=REF(C,1)<REF(天线1,1) AND C>天线1;
空1:=TFILTER(多,空,2);
多1:=TFILTER(多,空,1);

DRAWTEXT(空1,天线1*1.04,'空'),COLORGREEN;
DRAWTEXT(多1,天线3*0.96,'多'),COLORRED;
DRAWICON(空1,天线1*1.02,2);
DRAWICON(多1,天线3*0.98,1);

VAR11:=IF(YEAR>2999 AND MONTH>5,0,1);
VAR12:=IF(HIGH=CLOSE,1.10*CLOSE,HIGH)*VAR11;
VAR13:=IF(HIGH=CLOSE,0.90*CLOSE,LOW)*VAR11;
长期值2:=EMA((HIGH+LOW)/2,5);
顶部线2:=EMA(EMA(VAR12,6)*1.05,8);
底部线2:=EMA(EMA(VAR13,6)*0.97,8);
VAR18:=(HIGH+LOW+CLOSE)/3;
VARA2:=EMA(CLOSE,5);
VARB2:=EMA(CLOSE,10);
VARC2:=EMA(CLOSE,20);
VARD2:=EMA(CLOSE,50);
VARE2:=(VARA2+VARB2+VARC2+VARD2)/4;
天线12:=EMA(VARE2,60);
天线22:=EMA(VARE2,60)+EMA(VARE2,60)*0.03;
天线32:=EMA(VARE2,55)-EMA(VARE2,55)*0.03;
NOTEXT天线012:IF(天线12>REF(天线12,1),天线12,DRAWNULL),COLORMAGENTA;
NOTEXT天线112:IF(天线12<REF(天线12,1),天线12,DRAWNULL),COLORBLUE;
NOTEXT天线032:IF(天线32>REF(天线32,1),天线32,DRAWNULL),COLORMAGENTA;
NOTEXT天线132:IF(天线32<REF(天线32,1),天线32,DRAWNULL),COLORBLUE;
STICKLINE(天线12>REF(天线12,1),天线12,天线32,0,0),COLORMAGENTA;
STICKLINE(天线12<REF(天线12,1),天线12,天线32,0,0),COLORBLUE;
"""


def duokong(file_name,code):                      
    days=60
    Today=time.strftime("%Y-%m-%d-%H-%M-%S")
    year=int(Today.split('-')[0])
    month=int(Today.split('-')[1])
    pro = ts.pro_api()
    end_date_str=time.strftime("%Y%m%d")
    end_datetime = datetime.datetime.strptime(end_date_str, '%Y%m%d') 
    start_datetime=n_days_before(end_datetime,days)
    start_date_str=start_datetime.strftime("%Y%m%d")
    try:
        df = pro.daily(ts_code='{}.SZ'.format(str(code).zfill(6)), start_date=start_date_str, end_date=end_date_str)       
    except Exception as e:
        print(e)
        time.sleep(60) 
        df = pro.daily(ts_code='{}.SZ'.format(str(code).zfill(6)), start_date=start_date_str, end_date=end_date_str)
    df.set_index('trade_date',inplace=True)
    df.sort_index(inplace=True)   
    df.rename(columns={'vol': 'volume'},inplace=True)  
    df_new=df[["open","high","low","close","volume","amount"]]
    OPEN=df_new["open"].to_list() #open 是file open
    HIGH=df_new["high"].to_list()
    LOW=df_new["low"].to_list()
    CLOSE=df_new["close"].to_list()  
    VOLUME=df_new["volume"].to_list() 
    AMOUNT=df_new["amount"].to_list() 
    VAR2=[CLOSE[i]*1.1 if HIGH[i]==CLOSE[i] else HIGH[i] for i in range(len(CLOSE))]
    VAR3=[CLOSE[i]*0.9 if HIGH[i]==CLOSE[i] else LOW[i] for i in range(len(CLOSE))]
    短期值1=EMA(divide(ADD(HIGH,LOW),2),5)
    顶部线1=EMA(multiply(EMA(VAR2,6),1.05),8)
    底部线1=EMA(multiply(EMA(VAR3,6),0.97),8)
    VARA1=EMA(CLOSE,5)
    VARB1=EMA(CLOSE,10)
    VARC1=EMA(CLOSE,20)
    VARD1=EMA(CLOSE,50)
    VARE1=divide(ADDS(VARA1,VARB1,VARC1,VARD1),4)
    天线1=MA(VARE1,4)   
    # 天线2=ADD(MA(VARE1,5),multiply(MA(VARE1,5),0.03))
    天线3=subtraction(MA(VARE1,4),multiply(MA(VARE1,4),0.03))# 天线3<天线1 ,等距 MA(VARE1,4)*0.03
    # NOTEXT天线01=[天线1[i] if 天线1[i]>REF(天线1,1)[i] else nan for i in range(len(天线1))]#COLORRED
    # NOTEXT天线11=[天线1[i] if 天线1[i]<REF(天线1,1)[i] else nan for i in range(len(天线1))]#COLORGREEN
    # NOTEXT天线03=[天线3[i] if 天线3[i]>REF(天线3,1)[i] else nan for i in range(len(天线1))]#COLORRED
    # NOTEXT天线13=[天线3[i] if 天线3[i]<REF(天线3,1)[i] else nan for i in range(len(天线1))]#COLORGREEN
    RED_GREEN=["RED" if 天线1[i]>REF(天线1,1)[i] else "GREEN" for i in range(len(天线1))]#COLORRED
    
    空=[REF(CLOSE,1)[i]>REF(天线3,1)[i] and CLOSE[i]<天线3[i] for i in range(len(CLOSE))]
    多=[REF(CLOSE,1)[i]<REF(天线1,1)[i] and CLOSE[i]>天线1[i] for i in range(len(CLOSE))]
    空1=TFILTER(多,空,2) #用法:TFILTER(买入条件,卖出条件,N);过滤掉买入(卖出)信号发出后,下一个反向信号发出前的所有买入(卖出)信号,
                        # N=1表示仅对买入信号过滤;
                        # N=2表示仅对卖出信号过滤;
                        # N=0表示对买入和卖出信号都过滤,返回1,2表示买入或卖出条件成立;
                        # 同一K线上只能有一个信号;
    多1=TFILTER(多,空,1)

    # DRAWTEXT(空1,天线1*1.04,'空')#,COLORGREEN
    # DRAWTEXT(多1,天线3*0.96,'多')#,COLORRED
    # DRAWICON(空1,天线1*1.02,2)
    # DRAWICON(多1,天线3*0.98,1)

    VAR12=[CLOSE[i]*1.1 if HIGH[i]==CLOSE[i] else HIGH[i] for i in range(len(CLOSE))]
    VAR13=[CLOSE[i]*0.9  if HIGH[i]==CLOSE[i] else LOW[i] for i in range(len(CLOSE))]
    长期值2=EMA(divide(ADD(HIGH,LOW),2),5)
    顶部线2=EMA(multiply(EMA(VAR12,6),1.05),8)
    底部线2=EMA(multiply(EMA(VAR13,6),0.97),8)
    VAR18=divide(ADDS(HIGH,LOW,CLOSE),3)
    VARA2=EMA(CLOSE,5)
    VARB2=EMA(CLOSE,10)
    VARC2=EMA(CLOSE,20)
    VARD2=EMA(CLOSE,50)
    VARE2=divide(ADDS(VARA2,VARB2,VARC2,VARD2),4)
    天线12=EMA(VARE2,60)
    # 天线22=ADD(EMA(VARE2,60),multiply(EMA(VARE2,60),0.03))
    # 天线32=subtraction(EMA(VARE2,55),multiply(EMA(VARE2,55),0.03))
    # NOTEXT天线012:IF(天线12>REF(天线12,1),天线12#,COLORMAGENTA
    # NOTEXT天线112:IF(天线12<REF(天线12,1),天线12#,COLORBLUE
    # NOTEXT天线032:IF(天线32>REF(天线32,1),天线32#,COLORMAGENTA
    # NOTEXT天线132:IF(天线32<REF(天线32,1),天线32#,COLORBLUE
    # STICKLINE(天线12>REF(天线12,1),天线12,天线32,0,0)#,COLORMAGENTA
    # STICKLINE(天线12<REF(天线12,1),天线12,天线32,0,0)#,COLORBLUE
    MAGENTA_BLUE=["MAGENTA" if 天线12[i]>REF(天线12,1)[i] else "BLUE" for i in range(len(天线1))]
    duokongcangwei=[]
    for i in range(len(RED_GREEN)):#粉+红=满仓，粉+绿=六成，蓝+红=四成，蓝+绿=空仓
        if(RED_GREEN[i]=="RED" and MAGENTA_BLUE[i]=="MAGENTA"):
            duokongcangwei.append(1)
        elif(RED_GREEN[i]=="GREEN" and MAGENTA_BLUE[i]=="MAGENTA"):
            duokongcangwei.append(0.6)
        elif(RED_GREEN[i]=="RED" and MAGENTA_BLUE[i]=="BLUE"):
            duokongcangwei.append(0.4)
        else:
            duokongcangwei.append(0)

    output_File = open(file_name,'a+') 
    if len(duokongcangwei)>0:
        output_File.write('{},{},{}\n'.format(str(code).zfill(6),str(round(duokongcangwei[-1],2)),df_new['close'][-1]))
        output_File.flush()
    else:
        output_File.flush()
    return "%s complete"%str(code).zfill(6)


def multi_thread_duo_kong_check(file_name,code_list):
    """
    使用线程池，由系统自动分配线程数量，并打印线程目标函数的返回结果
    """  
    #在append之前先删除原数据表
    import concurrent.futures
    with concurrent.futures.ThreadPoolExecutor() as executor:     
        results=[ executor.submit(duokong,file_name,i) for i in code_list]
        for f in concurrent.futures.as_completed(results):
            print(f.result())      

if __name__=='__main__':
    path=os.getcwd()
    # df=pd.read_csv(path+'/after_process.csv')
    # df1=df[["code",'f10']]
    # df1.query('f10==True',inplace=True)
    # df1.drop(columns=['f10'],inplace=True)
    # df1.to_csv("f10_true.csv")
    df1=pd.read_csv(path+'/f10_true.csv')
    code_index_list=df1['code'].to_list()
    # file_name="{}.csv".format("duo_kong_cang_wei"+str(time.strftime("%Y_%m_%d_%H")))
    file_name="dkcw.csv"
    if os.path.exists(file_name): os.remove(file_name)
    output_File = open(file_name,'a+')
    output_File.write('{},{},{}\n'.format('code','dkcw','close'))
    output_File.flush()
    multi_thread_duo_kong_check(file_name,code_index_list)  
    #zljc由大到小排序
    df_res=pd.read_csv(file_name,encoding='unicode_escape') 
    df_res.columns=['code','dkcw','close']
    df_res.sort_values(by='dkcw',ascending=False,inplace=True)
    df_res.to_csv(file_name)
